import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import StorageUtils from './../../../app/storage';
import Utils from './../../../utils';
const DB = require('../../../app/db');

export default Reflux.createStore({

  listenables: [Actions],

  data: {
    ...PageConst,
    //滚动组件
    infs: null,

    //查询到的工程
    engls: [],

    //选中的工程
    currentEng: {},

    //搜索关键字
    keyword: '',

    //当前页数
    currentPage: 1,
    pageSize: 5,
    lastPage: false,
    //本弹窗是否显示
    fullpage_show: false,
    userInfo: {
      certNum: '',
      telNum: '',
      vcode: '',
      name:'',
      organName:''
    },
  },


  onSetinfs: function (obj) {
    this.data.infs = update(this.data.infs, {$set: obj});
    this.updateComponent();
  },

  initMode: function () {
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getStorage().get('user')}});
  },

  //初始化方法
  onInit: function () {
    this.data.fullpage_show = update(this.data.fullpage_show, {$set: false});
    this.data.currentPage = update(this.data.currentPage, {$set: 1});
    this.data.currentEng = update(this.data.currentEng, {$set: {}});
    this.updateComponent();
  },

  onEngSearch: function (params) {
    let t = this;
    console.info('1');
    console.info(params);
    this.onEngFetch({
      page: 1,
      jdfzr:'',
      keyword:params,
      size: 50,
    });
    t.updateComponent();
  },

  onEngFetch: function (params) {

    let t = this;

    params.page = t.data.currentPage;
    params.size = t.data.pageSize;
    params.jdfzr = t.data.userInfo.telNum;

    let resultUser = Utils.isEmptyObject(this.data.userInfo.telNum);
    if (!resultUser.success)
    {
      params.jdfzr = '13972608122';
    }
    else
    {
      params.jdfzr = t.data.userInfo.telNum;
    }
    DB.WechatAPI.getEng(params).then(
      function (content) {
        if (content.length <= 0) {
          console.info('未查找到数据');
        }
        else
        {
          t.data.engls = update(t.data.engls, {$set: content});
        }
        //如果请求后数据数量小于pageSize则设置为最后一页
        t.data.lastPage = true;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
      });
  },

  onShowPopup: function () {
    this.data.fullpage_show = update(this.data.fullpage_show, {$set: true});
    this.updateComponent();
  },

  onHidePopup: function () {
    this.data.fullpage_show = update(this.data.fullpage_show, {$set: false});
    this.updateComponent();
  },

  onSetEng: function (params) {
    this.data.currentEng = update(this.data.currentEng, {$set: params});
    this.updateComponent();
  },


  onFetch: function (params, cb) {
    let t = this;
    t.updateComponent();
    cb && cb(t.data);
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
